package org.apache.ocean.main.util;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class References<K> {
  private ConcurrentHashMap<K,Reference<K>> references = new ConcurrentHashMap<K,Reference<K>>();
  
  public List<Reference<K>> getExpired(long maxDuration) {
  	List<Reference<K>> expired = new ArrayList<Reference<K>>();
  	for (Reference<K> reference : references.values()) {
  		Date timestamp = reference.getTimestamp();
  		long refDuration = System.currentTimeMillis() - timestamp.getTime();
  		if (refDuration > maxDuration) {
  			expired.add(reference);
  		}
  	}
  	return expired;
  }
  
  public boolean hasRefs() {
  	return references.size() > 0;
  }
  
  public void add(K object) {
  	references.put(object, new Reference<K>(object));
  }
  
  public void remove(Object object) {
  	references.remove(object);
  }
  
  public static class Reference<K> {
  	private Date timestamp;
  	private K object;
  	
  	public Date getTimestamp() {
  		return timestamp;
  	}
  	
  	public Reference(K object) {
  		this.object = object;
  		timestamp = new Date(); 
  	}
  }
}
